﻿using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace FuiouCode {
    public class HttpUtils {
        public void Post(string url, Dictionary<string, object> map, StringBuilder result, string charset, string format = "XML") {
            // 创建httppost.
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            Encoding encoding;

            request.Method = "POST";

            request.ContentType = "application/x-www-form-urlencoded; ";

            if (format.Equals("XML")) {
                request.ContentType += "charset=GBK";

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                encoding = Encoding.GetEncoding(charset);
            } else {
                encoding = Encoding.UTF8;
            }

            string buffer = "";

            foreach (var m in map) {
                string value = m.Value + "";

                if (format.Equals("XML")) {
                    value = Utils.UrlEncode(value, encoding);
                }

                buffer += $"{m.Key}={value}&";
            }

            if (buffer.EndsWith("&")) {
                buffer = buffer.TrimEnd(new char[] { '&' });
            }

            byte[] postBody = encoding.GetBytes(buffer);

            using (Stream stream = request.GetRequestStream()) {
                stream.Write(postBody, 0, postBody.Length);
            }

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
                using (Stream stream = response.GetResponseStream()) {
                    using (StreamReader reader = new StreamReader(stream, encoding)) {
                        result.Append(reader.ReadToEnd());
                    }
                }
            }
        }
    }
}
